package com.blackhorse.mybatis.proxy;

import com.blackhorse.mybatis.config.Configuration;
import com.blackhorse.mybatis.config.Mapper;
import com.blackhorse.mybatis.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * DefaultSqlSession获取Dao代理对象的方式
 * 以及代理对象执行dao操作的具体细节
 */
public class MapperProxy implements InvocationHandler {

    private Map<String, Mapper> mappers;
    private Connection conn;

    public MapperProxy(Map<String, Mapper> mappers,Connection conn) {
        this.mappers = mappers;
        this.conn = conn;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1.获取方法名
        String methodName = method.getName();
        //2.获取方法所在类（接口）的全类名
        String className = method.getDeclaringClass().getName();

        String key = className + "." + methodName;
        Mapper mapper = mappers.get(key);
        //System.out.println(mappers);
        if(mapper==null){
            throw new IllegalArgumentException("传入参数有误!");
        }
        //执行sql
        Executor executor = new Executor();
        List<Object> list = executor.selectList(mapper, conn);
        return list;
    }
}
